<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Models\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';
    
    /**
     * 字段
     * @var string
     */
    private $field = 'name';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
    
    /**
     * @desc 重写登录，支持多字段登录
     */
    public function attemptLogin(Request $request)
    {
    	$username = $request->input('name');
    	$password = $request->input('password');
    	
    	$emailPattern = "#^([0-9A-Za-z\\-_\\.])@([0-9a-z]+\\.[a-z]{2}?)$#i";
    	$phonePattern = "#^1[34578]{1}\d{9}$#";
    	
    	if(preg_match($phonePattern, $username))
    	{
    		$this->field = 'telephone';
    	}else if (preg_match($emailPattern, $username))
    	{
    		$this->field = 'email';
    	}else 
    	{
    		$this->field  = 'name';
    	}
    	
    	$request[$this->field] = $username;
    	
    	$find_user = User::where([$this->field=>$username, 'status'=>'disabled'])->get();
    	
    	if(!$find_user->isEmpty())
    	{
    		return false;
    	}
    	return $this->guard()->attempt(
    		$request->only($this->username(), 'password'),$request->filled('remember')
    	);
    }
    
    public function username()
    {
    	return $this->field;
    }
    
    public function showLoginForm(Request $request)
    {
    	return view('auth.login');
    }
}
